import { dynamicLoader } from './index'
import { pluginManager } from '../plugins/pluginManager'
import type { Component } from 'vue'
import { ComponentType, ComponentCategory } from '@/views/pages/types/component'

export interface RegisteredComponent {
  type: ComponentType
  category: ComponentCategory
  component: Component
  label: string
  icon?: string | Component
  props: {
    base: Record<string, any>
    style: Record<string, any>
    baseSchema?: Record<string, any>
    styleSchema?: Record<string, any>
  }
}

export async function loadPageComponents(): Promise<RegisteredComponent[]> {
  try {
    // 加载文件系统中的组件
    const fsComponents = await dynamicLoader.loadComponents('pages/components', {
      recursive: true,
      pattern: 'index.vue'
    })

    // 转换本地组件
    const localComponents = fsComponents.map(({ component, metadata = {} }) => {
      // 确保组件类型和分类是有效的枚举值
      const type = Object.values(ComponentType).includes(metadata.type)
        ? metadata.type
        : ComponentType.FORM_INPUT
      
      const category = Object.values(ComponentCategory).includes(metadata.category)
        ? metadata.category
        : ComponentCategory.FORM

      return {
        type,
        category,
        component,
        label: metadata.label || formatComponentName(metadata.type || component.name || 'Unknown'),
        icon: metadata.icon,
        props: {
          base: metadata.props?.base || {},
          style: metadata.props?.style || {},
          baseSchema: metadata.props?.baseSchema,
          styleSchema: metadata.props?.styleSchema
        }
      }
    })

    // 获取插件组件
    const pluginComponents = pluginManager.getAllComponents()
    const remoteComponents = pluginComponents
      .filter(comp => comp.component || comp.virtual) // 只包含有效的组件
      .map(({ component, metadata }) => ({
        type: metadata.type,
        category: metadata.category,
        component: component!,
        label: metadata.label,
        icon: metadata.icon,
        props: metadata.props
      }))

    return [...localComponents, ...remoteComponents]
  } catch (error) {
    console.error('Failed to load components:', error)
    return []
  }
}

export async function loadLayouts(): Promise<Component[]> {
  try {
    const layouts = await dynamicLoader.loadComponents('layout', {
      recursive: true,
      pattern: 'index.vue'
    })

    return layouts.map(({ component }) => component)
  } catch (error) {
    console.error('Failed to load layouts:', error)
    return []
  }
}

// 格式化组件名称
function formatComponentName(name: string): string {
  return name
    .split(/[-_]/)
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ')
} 